package top.kikt.book.core.handlers

import okio.IOException
import org.jsoup.nodes.Document
import top.kikt.book.core.entity.BookMetaEntity
import top.kikt.book.core.entity.ChapterEntity
import top.kikt.book.core.entity.ChapterMetaEntity
import top.kikt.book.core.handlers.common.BaseBookHandler
import top.kikt.book.util.bookText
import top.kikt.book.util.metaContentWithProperty
import top.kikt.book.util.resolve

class Ibiquge : BaseBookHandler() {
    override val host: String
        get() = "www.ibiquge.la"

    override val hosts: List<String>
        get() = listOf(
            host,
            "ibiquges.org",
        )

    override fun parseBookMeta(document: Document, url: String): BookMetaEntity {
        val title = document.metaContentWithProperty("og:novel:book_name")
        val author = document.metaContentWithProperty("og:novel:author")
        val cover = document.metaContentWithProperty("og:image")
        return BookMetaEntity(title, url, url, author, cover)
    }

    override fun parseChapterMeta(document: Document, menuUrl: String): List<ChapterMetaEntity> {
        val chapterList = document.select("#list > dl > dd > a")
        return chapterList.mapIndexed { index, it ->
            val title = it.text()
            val url = menuUrl.resolve(it.attr("href"))
            ChapterMetaEntity(title, index, url, it)
        }
    }

    override fun parseChapter(chapterMetaEntity: ChapterMetaEntity): ChapterEntity {
        val doc = chapterMetaEntity.toDocument() ?: throw IOException("获取失败")
        val content = doc.select("#content")
        val text = content.bookText()
        return chapterMetaEntity.toChapterMetaEntity(text)
    }

}